package org.dromara.websocket.connection;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * Created by       PokerFace
 * Create Date      2023-7-10.
 * Email:
 * Version          1.0.0
 * <p>
 * Description:
 */
public class ConnectionManagerInboundHandlerAdapter extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(ConnectionManagerInboundHandlerAdapter.class);

    private ConnectionManager connectionManager;

    public ConnectionManagerInboundHandlerAdapter(ConnectionManager connectionManager)
    {
        this.connectionManager = connectionManager;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();

        logger.debug("Received Connection from IP["+inetSocketAddress.getAddress().getHostAddress()+"] PORT["+inetSocketAddress.getPort()+"]");
        if (connectionManager != null)
            connectionManager.receivedConnection(ctx);

        // call super method. Or call fireChannelActive(ctx)...
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        logger.debug("Connection Closed from IP["+inetSocketAddress.getAddress().getHostAddress()+"] PORT["+inetSocketAddress.getPort()+"]");
        if (connectionManager != null)
            connectionManager.removeConnection(ctx);

        super.channelInactive(ctx);
    }
}
